package com.gooluke.spring.util;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;

import java.lang.reflect.Parameter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.stream.Collectors;

/**
 * @author gooluke
 * description
 * datetime 2025-04-15 11:26
 */
public class ParamResolveUtil {

    /**
     * 解析请求体为对象
     */
    public static Object resolveRequestBody(HttpServletRequest req, Parameter parameter) {
        try {
            // 1. 读取请求体内容
            String body = req.getReader().lines().collect(Collectors.joining());
            if (body.trim().isEmpty()) {
                return new Object();
            }

            // 2. 解析为对象
            return JSONObject.parseObject(body, parameter.getType());
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse request body", e);
        }
    }

    public static Object resolveParam(Class<?> paramType, String paramName, String value) {
        Object result;
        try {
            if (value == null) {
                // 处理null值，如果是基本类型，赋予默认值
                result = getDefaultValueForPrimitive(paramType);
            } else if (String.class.isAssignableFrom(paramType)) {
                result = value;
            } else if (paramType == int.class || paramType == Integer.class) {
                result = Integer.parseInt(value);
            } else if (paramType == long.class || paramType == Long.class) {
                result = Long.parseLong(value);
            } else if (paramType == double.class || paramType == Double.class) {
                result = Double.parseDouble(value);
            } else if (paramType == float.class || paramType == Float.class) {
                result = Float.parseFloat(value);
            } else if (paramType == boolean.class || paramType == Boolean.class) {
                result = Boolean.parseBoolean(value);
            } else if (paramType == short.class || paramType == Short.class) {
                result = Short.parseShort(value);
            } else if (paramType == byte.class || paramType == Byte.class) {
                result = Byte.parseByte(value);
            } else if (paramType == char.class || paramType == Character.class) {
                if (value.length() == 1) {
                    result = value.charAt(0);
                } else {
                    throw new IllegalArgumentException("Character parameter must be exactly one character long");
                }
            }else if (paramType == BigDecimal.class) {
                result = new BigDecimal(value);
            } else if (paramType == BigInteger.class) {
                result = new BigInteger(value);
            } else if (paramType == LocalDate.class) {
                result = LocalDate.parse(value);
            } else if (paramType == LocalDateTime.class) {
                result = LocalDateTime.parse(value);
            } else if (paramType == LocalTime.class) {
                result = LocalTime.parse(value);
            } else {
                // 其他类型不支持
                throw new IllegalArgumentException("Unsupported parameter type: " + paramType.getName());
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Failed to convert parameter '" + paramName + "' with value '" + value + "' to type " + paramType.getName(), e);
        }
        return result;
    }

    private static Object getDefaultValueForPrimitive(Class<?> type) {
        if (!type.isPrimitive()) {
            return null;
        }

        if (type == int.class) return 0;
        if (type == long.class) return 0L;
        if (type == double.class) return 0.0;
        if (type == float.class) return 0.0f;
        if (type == boolean.class) return false;
        if (type == short.class) return (short) 0;
        if (type == byte.class) return (byte) 0;
        if (type == char.class) return '\0';

        return null;
    }

}
